//
//  HomeTableVC.swift
//  HengYouCai
//
//  Created by lwj on 2017/11/9.
//  Copyright © 2017年 lwj. All rights reserved.
//

import UIKit

///定义blcok
//typealias RunloopBlock = ((IndexPath) -> Bool)
private let cellID = "JCWFinancialFroductListVCCell"
class HomeTableVC: BaseTableViewController,WCarouselViewDelegate,SDCycleScrollViewDelegate,MenuDelegate,VipCellDelegate {
    func jumpToDetailVC(currentItem: Int) {
        let financial = FinancialDetailVC()
        if let dataArr = homeModel?.productList as? [ProjectModel] {
            let model = dataArr[currentItem]
            financial.homeModel = model
            financial.idStr = model.productsId
            self.navigationController?.pushViewController(financial, animated: true)
        }
        
    }
    /// 点击返回按钮 闪现白条问题
    var imageViewBar: UIView?
    /// 首页模型
    var homeModel : HomeModel?
    /// 表头
//    let homeHeaderView = HomeHeaderView(frame: CGRect(x: 0, y: 0, width: JCWSCREENW, height: 332))
    let homeHeaderView = HomeHeaderView(frame: CGRect(x: 0, y: 0, width: JCWSCREENW, height:368))

    /// 表尾
    lazy var customTableFooterView: UIView = {
        
        let temp = UIView(frame: CGRect(x: 0, y: 0, width: JCWSCREENW, height: 50 + kJcwGetTabbarHeight()))
        temp.backgroundColor = Normal_BackgroundColor
        let titleLab = UILabel()
        titleLab.tag = 1001
        titleLab.textColor = ColorFromRGBHex_WL(0x999999)
        titleLab.textAlignment = .center
        titleLab.font = Font_WL(11)
        temp.addSubview(titleLab)
        _ = titleLab.sd_layout()
            .topSpaceToView(temp,20)?
            .centerXEqualToView(temp)?
            .heightIs(11)?
            .autoWidthRatio(1)
        titleLab.setSingleLineAutoResizeWithMaxWidth(JCWSCREENW)
        
        //原始图片
        let srcImage = UIImage(named: "line")!
        
        //翻转图片的方向
        let flipImageOrientation = (srcImage.imageOrientation.rawValue + 4) % 8
        //翻转图片
        let flipImage =  UIImage(cgImage: srcImage.cgImage!, scale: srcImage.scale, orientation: UIImageOrientation(rawValue: flipImageOrientation)!)
        
        let lineLeftImg = UIImageView(image: flipImage )
        temp.addSubview(lineLeftImg)
        _ = lineLeftImg.sd_layout()
            .widthIs(50)?
            .heightIs(3)?
            .rightSpaceToView(titleLab,8)?
            .centerYEqualToView(titleLab)
        let lineRightImg = UIImageView(image: srcImage)
        temp.addSubview(lineRightImg)
        _ = lineRightImg.sd_layout()
            .widthIs(50)?
            .heightIs(3)?
            .leftSpaceToView(titleLab,8)?
            .centerYEqualToView(titleLab)
        return temp
    }()
    //  更改默认样式为
    convenience init() {
        self.init(style: .grouped)
    }
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        // 导航栏白色
//        self.navigationController?.navigationBar.setBackgroundImage( UIImage(named: "whiteImg"), for: UIBarMetrics.default)
        self.navigationController?.navigationBar.setBackgroundImage( UIImage(named: "touming"), for: UIBarMetrics.default)
        // 状态栏 字体白色
        UIApplication.shared.statusBarStyle = UIStatusBarStyle.lightContent
        self.navigationController?.navigationBar.shadowImage = UIImage()
        self.imageViewBar?.alpha = 0
        // 每次都刷新界面
        loadData()
        // 解决banner图滑到中间位置的问题
        self.homeHeaderView.bannerView.adjustWhenControllerViewWillAppera()
        // 如果是通过注册之后进首页的话 就弹出三部曲
        if UserDefaults.standard.string(forKey: KRegistSuccess) == KRegistSuccess {
            investRepare()
        }
        
    }
    override func viewDidLoad() {
        super.viewDidLoad()
        ///切换测试服务器
        if !isAppStore {
            self.navigationItem.leftBarButtonItem = UIBarButtonItem(title: "        ", style: .plain, target: self, action: #selector(leftBarClick))
            self.navigationItem.rightBarButtonItem = UIBarButtonItem(title: "        ", style: .plain, target: self, action: #selector(rightBarClick))
        }
//        //监听API Host的获取  ,  获取到host后更新首页数据
//        NotificationCenter.default.rac_addObserver(forName: "JCWBaseURL", object: nil).subscribeNext { [weak self](notify) in
//            if (self?.homeModel == nil && IPHost_Swift != ""){
//                self?.loadData()
//            }
//        }
        
        // 公司信息
        getCompareInfo()
        self.setNavigation()
        self.initTableView()
        self.view.jcw_showGifLoading()
//        self.loadData()
        weak var weakSelf = self
        self.tableView.mj_header = LWRefreshGifHeader(refreshingBlock: {
            weakSelf?.loadData()
        })

    }
    // 公司信息
    func getCompareInfo (){
        HYCNetService.getConmpareInfo(onSuccess: { (result) in
            let jsonDic = JSON(result as Any)
            let recordNum : String = jsonDic["recordNum"].stringValue
            let phone : String = jsonDic["phone"].stringValue
            let compony : String = jsonDic["compony"].stringValue
            let shareImgUrl:String = jsonDic["shareImgUrl"].stringValue
            
            
            UserDefaults.standard.set(phone, forKey: kPhone)
            UserDefaults.standard.set(compony, forKey: kCompony)
            UserDefaults.standard.set(recordNum, forKey: KRecordNum)
            UserDefaults.standard.set(shareImgUrl, forKey: KInviterImgUrl)
            UserDefaults.standard.synchronize()
//            UserDefaults.standard.set(nil, forKey: "")
            
            
        }) { (code, message) in
            UserDefaults.standard.set("", forKey: kPhone)
            UserDefaults.standard.set("", forKey: kCompony)
            UserDefaults.standard.set("", forKey: KRecordNum)
            
        }
    }
    /// 弹出三部曲
    func investRepare() {
        
            let investPrepare = InvestPrepareVC()
            _ = JCWAccountTrilogyAlertView(headerImageNamed: "login_title", callBack: {
                self.navigationController?.pushViewController(investPrepare, animated: true)
            })
            // 不管点击x还是去完成 都移除
            UserDefaults.standard.removeObject(forKey: KRegistSuccess)
    }
    ///输入地址
    func leftBarClick() {
        let alert = UIAlertController(title: "输入地址", message: "", preferredStyle: .alert)
        alert.addTextField(configurationHandler: nil)
        alert.addAction(UIAlertAction(title: "确定", style: .destructive, handler: { (action) in
            WLFileManager.saveUserData(alert.textFields![0].text, forKey: "JCWBaseURL")
        }))
        alert.addAction(UIAlertAction(title: "取消", style: .destructive, handler: { (action) in
        }))
        self.present(alert, animated: true, completion: nil)
    }
    ///选择地址
    func rightBarClick() {
        UIAlertController("", "切换服务器", [
            "https://api.ziyijinfu.com/",
            "http://192.168.0.240:8080/"], [], .actionSheet) { (index, baseUrl) in
                WLFileManager.saveUserData(baseUrl, forKey: "JCWBaseURL")
        }
       
        
    }
    /// 设置导航栏
    func setNavigation() {
        // 下个界面的back文字
        
//        self.imageViewBar = self.navigationController?.navigationBar.subviews.first
        self.navigationItem.title = ""
        // tableview自动下沉问题
        if #available(iOS 11.0, *) {
            self.tableView.contentInsetAdjustmentBehavior = .never
        } else {
            self.automaticallyAdjustsScrollViewInsets = false
        }
        self.imageViewBar = self.navigationController?.navigationBar.subviews.first
    }
    /// 设置tableView的基本属性
    func initTableView() {
        
        self.tableView.separatorStyle = .none
        self.tableView.rowHeight = 160
        self.tableView.tableHeaderView = homeHeaderView
        self.tableView.backgroundColor = Normal_BackgroundColor //UIColor.white
        self.tableView.tableFooterView = self.customTableFooterView
         self.tableView.register(JCWFinancialProductCell.self, forCellReuseIdentifier: cellID)
        self.tableView.register(HomeNewcomerCell.self, forCellReuseIdentifier: "reuseIdentifier")
//        self.tableView.register(ZYFinancialProductCell.self, forCellReuseIdentifier: "financialID")
//        self.tableView.register(HomeVipCell.self, forCellReuseIdentifier: "HomeVipCellID")
        self.tableView.register(HomeSectionHeaderView.self, forHeaderFooterViewReuseIdentifier: "homeSecHeaderID")
        self.tableView.register(UINib(nibName: "NoDataTableCell", bundle: nil), forCellReuseIdentifier: "NoDataTableCellID")
        homeHeaderView.articleView.delegate = self;
        homeHeaderView.bannerView.delegate = self
        homeHeaderView.menuDelegate = self
        
        /// 注册红包
        weak var weakSelf = self
        self.homeHeaderView.redPacket.rac_signal(for: UIControlEvents.touchUpInside).subscribeNext { (_) in
            let registerModel = MenuModel()
            registerModel.imageName = weakSelf?.homeModel?.registerImageUrl ?? ""
            registerModel.linkUrl = weakSelf?.homeModel?.registerUrl ?? ""
            registerModel.action = weakSelf?.homeModel?.registerAction ?? ""
            weakSelf?.menuTapDelegate(menuModel: registerModel)
        }
    }
   
    // MARK: - MenuDelegate
    func menuTapDelegate(menuModel: MenuModel) {
        if menuModel.action != "URL" {
            jumpToNextVCWithAction(action: menuModel.action, currentVC: self)
        }else{
            self.navigationController?.pushViewController(withUrlStr: menuModel.linkUrl, navTitle: menuModel.title, withHideBottomBarWhenPush: true, pop: false)
        }
    }
    
}
// MARK: - tableView的代理
extension HomeTableVC {
    override func numberOfSections(in tableView: UITableView) -> Int {
        // 推荐和 专享 都不为空的情况下 才显示 2个区 其他情况就一个
        if (homeModel != nil) {
            if ((homeModel?.vipProductModel != nil) || (homeModel?.starProduct != nil)) && (homeModel?.productList?.first != nil) {
                return 2
                
            }else {
                return 1
            }
        }else{
            return 1
        }
        
    }
    
    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        
        if (homeModel != nil) {
            // 有专享 并且是0区 返回vip的count
            if ((homeModel?.vipProductModel != nil) || (homeModel?.starProduct != nil)) && section == 0 {
                return 1
            }else{
                // 有推荐标  返回推荐标的count 否则返回1
                if let _ = homeModel!.productList?.first{
                    return homeModel!.productList.count
                }
                return 0
            }
        }else{
            return 1
        }
    }
    
    override func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        return 0.1
    }
    override func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        if homeModel != nil {
            
            if section == 0 && (homeModel?.starProduct != nil || homeModel?.vipProductModel != nil){
                return 43
            }
            if homeModel?.starProduct == nil && homeModel?.vipProductModel == nil && homeModel?.productList == nil {
                return 7.5
            }else if (homeModel?.productList != nil){
                if ((homeModel?.productList.count)! < 1) {
                    return 7.5

                }
                
            }
            return 43
        }else{
            
            return 7.5
            
        }
    }
    override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        if (homeModel != nil) {
            // 有专享 并且是0区 返回vip的count
            if ((homeModel?.vipProductModel != nil) || (homeModel?.starProduct != nil)) && indexPath.section == 0 {
                return 220
            }else{
                // 有推荐标  返回推荐标的count 否则返回1
                
                if  homeModel!.productList != nil {
                    
                    if (homeModel?.productList.count)! < 1{
                        
                        return 250

                    }
                    return 128
                }
                return 250
            }
        }else{
            return 250
        }
    }
    override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        tableView.deselectRow(at: indexPath, animated: true)
        let financial = FinancialDetailVC()

        if (homeModel != nil) {
            // 有专享 并且是0区 返回vip的count
            if ((homeModel?.vipProductModel != nil) || (homeModel?.starProduct != nil)) && indexPath.section == 0 {
                
                financial.homeModel = ((self.homeModel?.vipProductModel != nil) ? self.homeModel?.vipProductModel : self.homeModel?.starProduct)!
                
                financial.idStr = ((self.homeModel?.vipProductModel != nil) ? self.homeModel?.vipProductModel.productsId : self.homeModel?.starProduct.productsId)!
                
                self.navigationController?.pushViewController(financial, animated: true, withHideBottomBarWhenPush: true, pop: false)

            }else{
                // 有推荐标
                if homeModel?.productList != nil {
                    
                    if let _ = homeModel!.productList.first{
                        
                        if let dataArr = homeModel?.productList as? [ProjectModel] {
                            let model = dataArr[indexPath.row]
                            financial.homeModel = model
                            financial.idStr = model.productsId
                            self.navigationController?.pushViewController(financial, animated: true, withHideBottomBarWhenPush: true, pop: false)
                        }
                        
                    }
                }
                
            }
        }
        
        
    }
    
    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        if (homeModel != nil) {
            if ((homeModel?.vipProductModel != nil) || (homeModel?.starProduct != nil)) && indexPath.section == 0 {
                let cell = tableView.dequeueReusableCell(withIdentifier: "reuseIdentifier") as? HomeNewcomerCell
                
                if (homeModel?.vipProductModel != nil){
                    cell?.wl_configurationCellWithNew(homeModel?.vipProductModel, tableView, indexPath)

                }else{
                
                    cell?.wl_configurationCellWithStar(homeModel?.starProduct, tableView, indexPath)

                    
                }
                
                
                return cell!
            }else{
                
                if let _ = homeModel!.productList?.first{
                    let cell: JCWFinancialProductCell = tableView.dequeueReusableCell(withIdentifier: cellID) as! JCWFinancialProductCell
                   let dataArr = homeModel?.productList as! Array<ProjectModel>
                    cell.wl_configurationCell(dataArr, tableView, indexPath)
                    return cell

                }
                let cell  = tableView.dequeueReusableCell(withIdentifier: "NoDataTableCellID") as! NoDataTableCell
                cell.loadLocalImage()
                return cell
            }
        }else{
            let cell = tableView.dequeueReusableCell(withIdentifier: "NoDataTableCellID") as! NoDataTableCell
            cell.loadLocalImage()
            return cell
        }
        
        
        
    }
    
    
    override func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        
        if (homeModel != nil) {
            let headerView = tableView.dequeueReusableHeaderFooterView(withIdentifier: "homeSecHeaderID") as! HomeSectionHeaderView
//            headerView.imageUrl = homeModel?.productListImageUrl
            if ((homeModel?.vipProductModel != nil) || (homeModel?.starProduct != nil)) && section == 0 {
                // 有新手标 或是明星表
//                let view = UIView()
//                view.backgroundColor = Normal_458Color
//                return view
                // 有新手标 或是明星表

                let tagStr : String = ((homeModel?.vipProductModel != nil) ? homeModel?.vipProductModel.tags : homeModel?.starProduct.tags)!
                headerView.titlelLab.text = (homeModel?.vipTitle != nil) ? homeModel?.vipTitle : homeModel?.starTitle
                headerView.bottomLineView.isHidden = false
                headerView.tagsView.tagsStr("")
                
            }else if (homeModel?.productList == nil){
                let view = UIView()
                view.backgroundColor = UIColor.white
                return view
                
            }else if ((homeModel?.productList.count)! < 1){
                let view = UIView()
                view.backgroundColor = UIColor.white
                return view
                
            }else{
                // 有推荐标
                headerView.bottomLineView.isHidden = false
                
                headerView.titlelLab.text = homeModel?.productTitle
                headerView.tagsView.tagsStr("")
            }
            return headerView
        }
        let view = UIView()
        view.backgroundColor = UIColor.white
        return view
    }
    override func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
        return UIView()
        
        
    }
}
// MARK: - 通告与banner的代理
extension HomeTableVC {
    func numberOfItems(inCarouseView carouseView: WCarouselView!) -> Int {
        if (homeModel != nil) {
            return (homeModel?.articleList.count)!

        }else{
            
            return 0
        }
       
    }
    
    func carouseView(_ carouseView: WCarouselView!, indexOfItem index: Int) -> UIView! {
        let textLab = UILabel()
        textLab.font = Font_WL(12)
        textLab.textColor = Normal_333Color
        
        let articleModel:ArticleModel = homeModel?.articleList[index] as! ArticleModel
        
        textLab.text = articleModel.title
        return textLab
    }
    func carouseView(_ carouseView: WCarouselView!, indexOfItemWhenClick index: Int) {
        
        if homeModel?.articleList != nil {
             if  homeModel?.articleList.first != nil{
                
                let articleModel:ArticleModel = homeModel?.articleList[index] as! ArticleModel
                if articleModel.url != nil {
                   
                    if articleModel.url.count > 1{
                        self.navigationController?.pushViewController(BannerWebViewVC(urlStr: articleModel.url, title: "公告中心"), animated: true)
                        
                }
            }
        }
        
        }

    }
    func cycleScrollView(_ cycleScrollView: SDCycleScrollView!, didSelectItemAt index: Int) {
        
        if ((homeModel?.bannerList) != nil) {
            let bannerModel : BannerModel = (homeModel?.bannerList[index])!
            
            if bannerModel.link != nil {
                
                if bannerModel.link.count > 1{
                    
                    let bannerWebView = BannerWebViewVC(urlStr:   bannerModel.link
, title: bannerModel.title)

                    self.navigationController?.pushViewController(bannerWebView!, animated: true, withHideBottomBarWhenPush: true, pop: false)

                }
                
            }
            
        }
        
    }
    
}


// MARK: - 列表数据请求
extension HomeTableVC {
    fileprivate func loadData() {
        
        guard IPHost_Swift != "" else {
            return;
        }
        weak var weakSelf = self
        
        HYCNetService.mallHome(withDict: nil, onSuccess: { (result) in
            //
            self.tableView.mj_header?.endRefreshing()

           self.view.hideHUDLoading(0)
            self.homeModel = HomeModel.mj_object(withKeyValues: result)
//            self.navigationItem.title = self.homeModel?.title
            var imgUrlArr = [String]()

            if let model = HomeModel.mj_object(withKeyValues: result){
                model.bannerList.forEach({
                    imgUrlArr.append($0.url ?? "")
                })
            }
            
            
//            "riskShow":true,
//            "safeShow":false,
//            "safe2Show":true,
//            "registerShow":false,
//            "inviteShow":true,
//            "helpCenterShow":false,
//            "platformIntroShow":true,
            //            self.homeHeaderView.
            var menuArr = [MenuModel]()
            if (self.homeModel?.platformIntroShow ?? false)!{
                let model = MenuModel()
                model.imageName = self.homeModel?.platformIntroIcon ?? ""
                model.title =  self.homeModel?.platformIntroTitle ?? "" //"平台简介"
                model.linkUrl = (self.homeModel?.platformIntroUrl ?? "")!
                model.action = self.homeModel?.platformIntroAction ?? ""
                menuArr.append(model)
            }
            if (self.homeModel?.safeShow ?? false)!{
                let model = MenuModel()
                model.imageName =  self.homeModel?.safeIcon ?? ""//"insurance"
                model.title =  self.homeModel?.safeTitle ?? "" //"安全保障"
                model.linkUrl = (self.homeModel?.safeUrl ?? "")!
                model.action = self.homeModel?.safeAction ?? ""
                menuArr.append(model)
            }
            
            if (self.homeModel?.guideShow ?? false)!{
                let model = MenuModel()
                model.imageName =  self.homeModel?.guideIcon ?? "" //"home_datd"
                model.title =  self.homeModel?.guideTitle ?? ""//"新手指引"
                model.linkUrl = self.homeModel?.guideUrl ?? ""
                model.action = self.homeModel?.guideAction ?? ""
                menuArr.append(model)
            }
            if (self.homeModel?.inviteShow ?? false)!{
                let model = MenuModel()
                model.imageName =  self.homeModel?.inviteIcon ?? ""//"invitehome"
                model.title =  self.homeModel?.inviteTitle ?? ""//"好友邀请"
                model.linkUrl = self.homeModel?.inviteUrl ?? "" //"invitehome"
                model.action = self.homeModel?.inviteAction ?? ""
                menuArr.append(model)
            }
            if (self.homeModel?.helpCenterShow ?? false)!{
                let model = MenuModel()
                model.imageName =  self.homeModel?.helpCenterIcon ?? ""//"home_help"
                model.title =  self.homeModel?.helpCenterTitle ?? ""//"帮助中心"
                model.linkUrl = self.homeModel?.helpCenterUrl ?? ""
                model.action = self.homeModel?.helpCenterAction ?? ""
                menuArr.append(model)
            }
            
           
           
           
            weakSelf?.homeHeaderView.setMenuView(menuArr)
            let footLabel:UILabel = weakSelf?.customTableFooterView.viewWithTag(1001) as! UILabel
            footLabel.text = self.homeModel?.homeSlogan
            weakSelf?.homeHeaderView.redPacket.isHidden = !(weakSelf?.homeModel?.registerShow)!
            if ((weakSelf?.homeModel?.registerShow)!){
                let url = URL(string: (weakSelf?.homeModel?.registerImageUrl)!)
                weakSelf?.homeHeaderView.redPacket.kf_setImage(with: ImageResource(downloadURL: url!), for: .normal)
            }
            weakSelf?.homeHeaderView.height = weakSelf?.homeModel?.registerShow == false ? 290 : 368
            self.homeHeaderView.bannerView.imageURLStringsGroup = imgUrlArr
            self.homeHeaderView.articleView.reloadData()
            self.tableView.reloadData()
            
            //本地缓存 无网络时图片
            WLTool.saveNetWorkImage(toLocal: weakSelf?.homeModel?.homeBackgroundImageUrl, withImageName: "homeBackgroundImageUrl")
            
            
            
        }) { (code, errMsg) in
            //
            self.view.hideHUDLoading(0)

            self.tableView.mj_header?.endRefreshing()

            self.tableView.reloadData()
        }
        
    }
}



